package com.vains.controller;

import com.vains.bean.Result;
import com.vains.constant.ApplicationNameConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 登录接口
 *
 * @author vains
 * @date 2021/4/6 18:19
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(tags = "OAuth2的一些接口")
@SessionAttributes("authorizationRequest")
public class OauthController {

    @GetMapping("/oauth/error")
    @ApiOperation("获取oauth2异常，由框架自动调用")
    public Result<?> error(HttpServletRequest request) {
        Object error = request.getAttribute("error");
        log.warn("捕获到oauth2异常：{}", error);
        if (error instanceof OAuth2Exception) {
            OAuth2Exception oauthError = (OAuth2Exception) error;
            return Result.oauth2Error(oauthError.getMessage(), oauthError);
        } else if (error instanceof Result) {
            return (Result<?>) error;
        }
        return Result.error("未知异常.");
    }

    @ApiOperation("自定义授权页面")
    @RequestMapping("/oauth/confirm_access")
    public ModelAndView confirmAccess(Map<String, Object> model, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
        @SuppressWarnings("unchecked")
        Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ?
                model.get("scopes") : request.getAttribute("scopes"));
        view.addObject("scopes", scopes);
        view.addObject("clientId", authorizationRequest.getClientId());
        view.addObject("applicationName", ApplicationNameConstants.AUTH_SERVER_NAME);
        view.setViewName("approval");
        return view;
    }

}
